package rest

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"monoblog/common"
	"monoblog/domain/auth"
	"monoblog/domain/dto"
	"monoblog/domain/service"
)

/*
专栏接口
*/

func SectionAdd(ctx *gin.Context) {
	var form dto.SectionReqForm
	if err := ctx.ShouldBind(&form); err != nil {
		common.Fail(ctx, "Body数据绑定失败", err)
		return
	}
	//初始化校验器并执行字段校验
	validate := validator.New()
	if err := validate.Struct(form); err != nil {
		common.Fail(ctx, "参数校验失败", err)
		return
	}

	if user, ok := ctx.Get("user"); ok {
		form.LoginUser = user.(*auth.LoginUser)
	} else {
		common.Fail(ctx, "用户未登录", errors.New("user not login"))
		return
	}

	id, err := service.GetSectionService().Add(ctx, form)
	if err != nil {
		common.Fail(ctx, "添加专栏失败", err)
		return
	}
	common.Success(ctx, id)
}

func SectionUpdate(ctx *gin.Context) {
	id := ctx.Param("id")

	var form dto.SectionReqForm
	if err := ctx.ShouldBind(&form); err != nil {
		common.Fail(ctx, "Body数据绑定失败", err)
		return
	}

	//初始化校验器并执行字段校验
	validate := validator.New()
	if err := validate.Struct(form); err != nil {
		common.Fail(ctx, "参数校验失败", err)
		return
	}

	if user, ok := ctx.Get("user"); ok {
		form.LoginUser = user.(*auth.LoginUser)
	} else {
		common.Fail(ctx, "用户未登录", errors.New("user not login"))
		return
	}

	err := service.GetSectionService().UpdateByID(ctx, id, form)
	if err != nil {
		common.Fail(ctx, "更新专栏失败", err)
		return
	}
	common.Success(ctx, nil)
}

func SectionDelete(ctx *gin.Context) {
	id := ctx.Param("id")

	if _, ok := ctx.Get("user"); !ok {
		common.Fail(ctx, "用户未登录", errors.New("user not login"))
		return
	}

	err := service.GetSectionService().DeleteByID(ctx, id)
	if err != nil {
		common.Fail(ctx, "删除专栏失败", err)
		return
	}
	common.Success(ctx, nil)
}

func SectionFindList(ctx *gin.Context) {
	categories, err := service.GetSectionService().FindList(ctx)
	if err != nil {
		common.Fail(ctx, "查询专栏列表失败", err)
		return
	}
	common.Success(ctx, categories)
}
